﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using up7.db.model;
using up7.db.utils;

namespace up7.db.biz
{
    /// <summary>
    /// 文件夹层级结构类
    /// 用法：
    /// FolderSchema fs = new FolderSchema();
    /// fs.create();//在文件夹初始化时创建
    /// fs.addFile();//在上传第一块子文件数据时添加信息。
    /// 更新记录：
    ///     2020-11-18 创建
    /// </summary>
    public class FolderSchema
    {
        /// <summary>
        /// 创建结构文件
        /// pathSvr/scheme.txt
        /// </summary>
        /// <param name="dir"></param>
        public bool create(FileInf dir)
        {
            String file = dir.schemaFile();
            var val = JsonConvert.SerializeObject(dir);
            File.WriteAllText(file, val + "\n");
            return File.Exists(file);
        }

        /// <summary>
        /// 添加一条记录
        /// </summary>
        /// <param name="f"></param>
        public void addFile(FileInf f)
        {
            String root = "";
            if (!string.IsNullOrEmpty(f.pathRel)) root = f.pathSvr.Replace(f.pathRel, "");

            //guid/Soft/folder1/QQ.exe->/guid/Soft
            root = Path.GetDirectoryName(root);
            //guid/
            root = Path.GetDirectoryName(root);
            String file = Path.Combine(root, "schema.txt");
            f.pathLoc = f.pathLoc.Replace("\\", "/");
            f.pathRel = f.pathRel.Replace("\\", "/");
            f.pathSvr = f.pathSvr.Replace("\\", "/");
            var val = JsonConvert.SerializeObject(f);
            if (File.Exists(file)) FileTool.appendSafe(file, val + "\n");
        }
    }
}